package com.clam314.lame;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.TypedArray;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.Toast;

import com.tuotu.gps.R;
import com.tuotu.gps.RecordActivity2;
import com.tuotu.gps.utils.GpsLocationUtils;
import com.tuotu.gps.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by clam314 on 2016/7/21
 */
public class MediaRecorderButton extends Button implements MediaRecorderListener{

    //用于标识按钮不同状态，显示不同的样式
    private static final int BEFORE_RECORD = 108;
    private static final int NORMAL_STATUS = 109;
    private static final int RECORDING_STATUS = 110;
    private static final int CANCEL_STATUS = 111;
    private static final int DISTANCE_Y_CANCEL = 50;

    //设置录音的最短时长,过短的录音当做取消
    private static final long timeDistance = 500;

    //延迟开始录音的时间，防止连按，多次触发录音功能导致阻塞主线程
    private static final long DELAYED_TIME = 3*100;

    //用于标识录音的不同状态
    public static final int RECORDER_SUCCESS = 209;
    public static final int START_RECORDER = 200;
    public static final int END_RECORDER_60S = 260;
    public static final int END_RECORDER_TOO_SHORT = 270;
    public static final int END_RECORDER_CANCEL = 280;
    private static final int COUNT_STATUS = 180;


    private long startTime = 0;
    private long downTime = 0;
    private boolean cancelCount = false;
    private boolean wantCancel = false;
    private boolean recording = false;
    private boolean overMaxRecodeTime = false;
    private String bastPath;
    private RecorderStatusListener statusListener;
    private RecorderFinishListener finishListener;
    private int mSecond = 0;
    private int typeRecord;
    private  Context mContext;
    Date date;
    String mp3Name;

    GpsLocationUtils gpsLocationUtils;

    private Handler handler = new Handler(Looper.getMainLooper()){
        static final int COUNT_TIME_END = 0;
        int count = 60;//限制录音的最大时长，单位秒
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case COUNT_STATUS:
                    if(cancelCount){
                        removeMessages(COUNT_STATUS);
                        count = 60;
                        if(statusListener != null) statusListener.onEnd(END_RECORDER_CANCEL);
                        break;
                    }
                    count--;
                    mSecond = 60 - count;
                    if(statusListener != null) statusListener.onEnd(count);
                    if (count == COUNT_TIME_END) {
                        removeMessages(COUNT_STATUS);
                        changeBackground(NORMAL_STATUS);
                        overMaxRecodeTime = true;
                        endRecorder(false);
                        if(statusListener != null) statusListener.onEnd(END_RECORDER_60S);
                        count = 60;
                        return;
                    }
                    sendEmptyMessageDelayed(COUNT_STATUS, 1000);
                    break;
                case START_RECORDER:
                    startRecorder();
                    break;
            }
        }
    };

    public void setGpsLocationUtils(GpsLocationUtils gpsLocationUtils) {
        this.gpsLocationUtils = gpsLocationUtils;
    }

    public MediaRecorderButton(Context context) {
        super(context);
        mContext=context;
        init();
    }

    public MediaRecorderButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
//        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MediaRecorderButton);
//        typeRecord =ta.getInt(R.styleable.MediaRecorderButton_typeRecord,0);
//        LogUtil.print("MediaRecorderButton init typeRecord=2="+typeRecord);
        init();
    }

    public MediaRecorderButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext=context;
        init();
    }

    private void init() {
//        bastPath = getBasePath();
        changeBackground(NORMAL_STATUS);
    }

    public  String getBasePath() {
        String strPath = null;
        if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            strPath = getContext().getFilesDir() + "/" + "gps";
        } else{
            strPath = Environment.getExternalStorageDirectory() + "/" + "gps";
        }
        File dir = new File(strPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        return strPath;
    }

    public void setBastPath(String bastPath){
        this.bastPath = bastPath;
    }

    public void setFinishListener(RecorderFinishListener listener){
        finishListener = listener;
        LameMp3Manager.instance.setMediaRecorderListener(this);
    }

    public void setRecorderStatusListener(RecorderStatusListener listener){
        if(listener != null){
            this.statusListener = listener;
        }
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");//设置日期格式

    private void startRecorder( ){
        setSelected(true);
        overMaxRecodeTime = false;
        mSecond = 0;
        date=new Date();
        mp3Name=format.format(date);
        LogUtil.print("MediaRecorderButton startRecorder typeRecord=="+typeRecord);
        if(typeRecord==0){
            bastPath= RecordActivity2.GPS_DIR_TODAY+mp3Name+".mp3";
        }
//        if(statusListener != null) statusListener.beforeStart();
        if(statusListener != null) statusListener.onStart(START_RECORDER,mp3Name,date,typeRecord);
        startTime = System.currentTimeMillis();
        recording = true;
        cancelCount = false;
        startRingVoice();
    }

    private void startRingVoice(){
//        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//        Ringtone rt = RingtoneManager.getRingtone(getApplicationContext(), notification);
//        rt.play();
        try {
            AssetFileDescriptor afd=mContext.getAssets().openFd("ring.mp3");
            MediaPlayUtil.release();
            MediaPlayUtil.init(mContext);
            MediaPlayUtil.playSound(afd, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    LogUtil.print("startvoice -----onCompletion typeRecord=="+typeRecord);
                    MediaPlayUtil.release();

                    //播放完提示音之后，开始录音
                    LameMp3Manager.instance.startRecorder(bastPath,typeRecord);
                    handler.sendEmptyMessage(COUNT_STATUS);
                    if(isSelected()){
                        changeBackground(RECORDING_STATUS);
                    }
//                    if(statusListener != null) statusListener.onStart(START_RECORDER,mp3Name,date,typeRecord);
                    if(statusListener != null) statusListener.beforeStart();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.print("startvoice ex=="+e.toString());
        }
    }
    private void endRecorder(boolean wantCancel){
        setSelected(false);
        LogUtil.print("bt--- endRecorder recording=="+recording);
        if(recording){
            boolean tooShort = System.currentTimeMillis() - startTime < timeDistance;
            if(tooShort){
                LogUtil.print("bt--- endRecorder tooShort==");
                LameMp3Manager.instance.cancelRecorder();
                if(statusListener != null) statusListener.onEnd(END_RECORDER_TOO_SHORT);
//                LameMp3Manager.instance.stopRecorder(); //录音时间短也保存文件
            }else if(wantCancel){
                LogUtil.print("bt--- endRecorder wantCancel==");
                LameMp3Manager.instance.cancelRecorder();
                this.cancelCount = true;
                this.wantCancel = false;
            }else {
                LogUtil.print("bt--- endRecorder stopRecorder==");
                LameMp3Manager.instance.stopRecorder();
            }
            recording = false;
        }
    }

    public void recordStart(int typeRecord){
        LogUtil.print("recordStart typeRecord =="+typeRecord);
        if(null!=gpsLocationUtils){
            Location mLocation=gpsLocationUtils.getLastLocation();
            if(null==mLocation){
                if(statusListener != null) statusListener.noLocation();
            }else {
                LogUtil.print("recordStart isSelected =="+isSelected());
                if(isSelected()){
                    setSelected(false);
                    handler.removeMessages(START_RECORDER);
//                    changeBackground(NORMAL_STATUS);
                    //录音时间没有超时才停止录音
                    LogUtil.printE("overMaxRecodeTime=="+overMaxRecodeTime);
                    if(!overMaxRecodeTime){
                        endRecorder(wantCancel);
                        cancelCount = true;
                    }
                }else {
                    this.typeRecord=typeRecord;
                    setSelected(true);
                    LameMp3Manager.instance.stopRecorder();//开始录音前，先停止所有,初始化
                    changeBackground(BEFORE_RECORD);
                    handler.removeMessages(START_RECORDER);
                    handler.sendEmptyMessageDelayed(START_RECORDER, DELAYED_TIME);
                }
            }
        }else {

        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(System.currentTimeMillis() - downTime > 1000){
                    downTime = System.currentTimeMillis();
                    recordStart(0);
                }
//                downTime = System.currentTimeMillis();
//                changeBackground(RECORDING_STATUS);
//                handler.removeMessages(START_RECORDER);
//                if(null!=gpsLocationUtils){
//                  Location mLocation=gpsLocationUtils.getLastLocation();
//                  if(null==mLocation){
//                      if(statusListener != null) statusListener.noLocation();
//                  }else {
//                      handler.sendEmptyMessageDelayed(START_RECORDER, DELAYED_TIME);
//                  }
//                }
                break;
            case MotionEvent.ACTION_MOVE:
//                if(wantToCancel(x, y)){
//                    if(isSelected())
//                        changeBackground(CANCEL_STATUS);
//                    wantCancel = true;
//                }
                break;
            case MotionEvent.ACTION_UP:
//                recordStart(0);
                break;
            case MotionEvent.ACTION_CANCEL:
//                changeBackground(NORMAL_STATUS);
//                if(System.currentTimeMillis() - downTime < DELAYED_TIME){
//                    handler.removeMessages(START_RECORDER);
//                }
//                //录音时间没有超时才停止录音
//                if(!overMaxRecodeTime){
//                    endRecorder(wantCancel);
//                    cancelCount = true;
//                }
        }
        return super.onTouchEvent(event);
    }

    private boolean wantToCancel(int x, int y) {
        return x < 0 || x > getWidth() || y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL;
    }

    private void changeBackground(int status){
        switch (status){
            case NORMAL_STATUS:
//                setBackgroundResource(R.drawable.button_recordnormal);
//                setText(typeRecord==0?"采集数据": typeRecord==1?"补充录音":"重新录音");
                setText("采集数据");
                break;
            case RECORDING_STATUS:
//                setBackgroundResource(R.drawable.button_recording);
//                setText("点击结束");
                break;
            case CANCEL_STATUS:
//                setBackgroundResource(R.drawable.button_recording);
//                setText("取消");
                break;
            case BEFORE_RECORD:
//                setText("正在准备");
                break;
        }
    }

    @Override
    public void onRecorderFinish(int status, String path) {
        if(finishListener != null){
            LogUtil.print("onRecorderFinish typeRecord =="+typeRecord);
            finishListener.onRecorderFinish(status,path, String.valueOf(mSecond),typeRecord);
        }
    }

    public interface RecorderStatusListener{
        void beforeStart();
        void onStart(int status,String mp3Name,Date date,int typeRecord);
        void onEnd(int status);
        void noLocation();
    }

    public interface RecorderFinishListener {
        void onRecorderFinish(int status, String filePath, String second,int typeRecord);
    }
}
